package com.zdjx.manage;

import com.zdjx.robot.RobotSence;
import com.zdjx.scene.BaseScene;
import com.zdjx.scene.ChatScene;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 管理机器人线程的创建和执行
 */
public class RobotManage {

    private static Logger logger = Logger.getLogger(RobotManage.class);

    private Integer startPort = 21000;   //起始端口
    private Integer robotNum;            //机器人数量
    private Integer robotnumPerSec;      //每秒执行机器人个数
    private Integer tranTotal;           //机器人执行次数，<=0表示无限循环
    List<BaseScene> scenes = new ArrayList<BaseScene>();  //事务集

    //全参构造
    public RobotManage(Integer startPort, Integer robotNum, Integer robotnumPerSec, Integer tranTotal) {
        this.startPort = startPort;
        this.robotNum = robotNum;
        this.robotnumPerSec = robotnumPerSec;
        this.tranTotal = tranTotal;
    }

    //不带端口
    public RobotManage(Integer robotNum, Integer robotnumPerSec, Integer tranTotal) {
        this.robotNum = robotNum;
        this.robotnumPerSec = robotnumPerSec;
        this.tranTotal = tranTotal;
    }

    //激活机器人
    public void actRobot(){
        logger.debug("start to set up robot....");
        //使用线程池装载
        ExecutorService pool = Executors.newFixedThreadPool(robotNum);
        //定义许可用于限制线程执行速率
        Semaphore semaphore = new Semaphore(robotnumPerSec);
        scenes.add(new ChatScene()); //todo
        //线程数
        for(int i = 0; i < robotNum; ++i){
            String gname = "tester" + i;
            pool.execute(new Thread(new RobotSence(semaphore, scenes, gname)));
        }

        //执行次数判定
        if(tranTotal > 0){
            logger.debug("execute\t" + tranTotal + "\ttimes......");
            for (int i = 0;i < tranTotal;++i){
                for(int j = 0; j < robotNum/robotnumPerSec; ++j){
                    try {
                        //每隔一秒释放xxx个许可证
                        Thread.sleep(1000);
                        semaphore.release(robotnumPerSec);
                        System.out.println("start---------------------------------------------------------------");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }else { //无限循环
            logger.debug("infinite loop......");
            while (true){
                try {
                    //每隔一秒释放xxx个许可证
                    Thread.sleep(1000);
                    semaphore.release(robotnumPerSec);
                    System.out.println("start---------------------------------------------------------------");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
